<template>
  <div>
    <div
      style="
        font-style: italic;
        height: 60px;
        padding-top: 3%;
        margin-top: 2%;
        font-size: 1.5em;
      "
    >
      修改个人信息
    </div>
    <el-form
      :label-position="labelPosition"
      label-width="80px"
      :model="formLabelAlign"
    >
      <el-form-item label="昵称">
        <el-input v-model="formLabelAlign.nickname"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="formLabelAlign.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="formLabelAlign.phone"></el-input>
      </el-form-item>
      <el-form-item label="当前头像">
        <el-row>
          <el-col :span="8">
            <el-avatar
              :src="formLabelAlign.userImg"
              style="height: 100px; width: 100px"
            ></el-avatar>
          </el-col>
          <el-col :span="8">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="uploadingImg" :src="uploadingImg" class="avatar" />
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="submitForm(formLabelAlign)"
          icon="el-icon-check"
          style="
            background-color: rgb(200, 9, 9);
            border-color: rgb(200, 9, 9);
            color: white;
          "
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { jwtDecode } from "jwt-decode";
import axios from "axios";

export default {
  data() {
    return {
      uploadingImg: null,
      labelPosition: "right",
      formLabelAlign: {
        userId: "",
        nickname: "",
        password: "",
        phone: "",
        userImg: "",
      },
      userId: "", // 在 data 中添加 userId
    };
  },
  computed: {
    uploadUrl() {
      return `http://localhost:8081/user/updateimg?userId=${this.formLabelAlign.userId}&newimg=${this.uploadingImg}`;
    },
  },
  mounted() {
    const token = localStorage.getItem("token");

    if (!token) {
      console.log("没有 token，跳转到登录页面");
      this.$router.push("/login");
      return;
    }

    // 解码 token，提取 userId
    try {
      console.log(token); // 输出获取到的token
      console.log(jwtDecode(token)); // 解析JWT并输出

      const decoded = jwtDecode(token); // 使用新的jwtDecode进行解析
      this.userId = decoded.userId; // 获取 userId
      console.log("用户ID:", this.userId);

      // 请求用户信息
      axios
        .get("/user/findUserById", {
          params: { userId: this.userId },
          headers: {
            Authorization: `Bearer ${token}`, // 将 token 加入请求头
          },
        })
        .then((res) => {
          console.log(res.data);
          this.formLabelAlign.nickname = res.data.data.user.nickname;
          this.formLabelAlign.password = res.data.data.user.password;
          this.formLabelAlign.phone = res.data.data.user.phone;
        })
        .catch((error) => {
          console.log(error);
        });
    } catch (error) {
      console.error("Token 解码失败:", error);
    }
  },

  methods: {
    submitForm(formLabelAlign) {
      // 提交表单前的简单验证
      if (!formLabelAlign.nickname || !formLabelAlign.password) {
        this.$message.error("所有字段都必须填写");
        return;
      }

      // 使用 axios 发送 POST 请求来更新用户信息
      axios
        .post(
          "/user/updateUser",
          {
            userId: this.userId,
            password: formLabelAlign.password,
            nickname: formLabelAlign.nickname,
            phone: formLabelAlign.phone,
            userImg: formLabelAlign.userImg,
          },
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`, // 在请求头中添加 token
              accept: "*/*",
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          if (res.data.code === 200) {
            // 更新成功后，可以跳转或执行其他逻辑
            this.$router.push("/user-about/user-detail");
            return this.$message.success("更新成功");
          } else {
            return this.$message.error(res.data.message || "更新失败");
          }
        })
        .catch((error) => {
          console.error("提交表单失败:", error);
          this.$message.error("网络错误，请稍后再试");
        });
    },
    // 修改头像相关
    handleAvatarSuccess(res) {
      if (
        res.data &&
        res.data.data &&
        res.data.data.user &&
        res.data.data.user.userImg
      ) {
        this.uploadingImg = res.data.data.user.userImg;
        this.formLabelAlign.userAvatar = this.uploadingImg;
      } else {
        this.$message.error("上传失败，请重试");
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //修改头像的请求地址参数配置
    getUploadParams() {
      return {};
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 2px solid red;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: whitesmoke;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: red;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-form {
  border: whitesmoke solid 4px;
  /* background: url("../../assets/1.jpg"); */
  margin-top: 20px;
  padding-top: 10px;
}
.el-form-item {
  padding-top: 15px;
  padding-left: 300px;
  padding-right: 400px;
}
</style>
